package cp5_jdbc;

import util.Constants;

import java.sql.*;
import java.util.Scanner;

public class PreparedStatementTest {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        // 1. 加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");

        // 2. 获取数据库连接
        Connection conn = DriverManager.getConnection(Constants.URL, Constants.USERNAME, Constants.PASSWORD);
        Scanner input = new Scanner(System.in);
        System.out.printf("请输入用户名：");
        String name = input.next();
        System.out.printf("请输入密码:");
        String pass = input.next();
        String sql = "select * from userinfo where account=? and password=? limit 1";
        // 3.创建statement
        PreparedStatement pst = conn.prepareStatement(sql);// 通过sql语句预编译要执行的sql对象
        // 4.设置sql中执行需要的参数
        pst.setString(1,name); // 参数从1开始
        pst.setString(2,pass);

        ResultSet rs = pst.executeQuery();
        // 判断是否有数据
        if(rs.next()){
            String nickname = rs.getString("nickname");
            System.out.println("登录成功，欢迎 " + nickname);
        }else{
            System.out.println("用户名或者密码错误");
        }
        // 关闭
        rs.close();
        pst.close();
        conn.close();
    }
}
